﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace RemoteScriptingLibrary
{
    public class BrowserHelper
    {
        public static string RetrieveData(string url)
        {
            // used to build entire input
            StringBuilder stringBuilder = new StringBuilder();

            // used on each read operation
            byte[] aBuffer = new byte[8192];

            try
            {

                // prepare the web page we will be asking for
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = 5000; // milliseconds
                // execute the request

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.ContentLength > 150000)
                {
                    return string.Empty;
                }

                // we will read data via the response stream
                using (Stream resStream = response.GetResponseStream())
                {
                    resStream.ReadTimeout = 5000;

                    string tempString = null;
                    int count = 0;

                    do
                    {
                        // fill the buffer with data
                        count = resStream.Read(aBuffer, 0, aBuffer.Length);

                        // make sure we read some data
                        if (count != 0)
                        {
                            // translate from bytes to ASCII text
                            tempString = Encoding.ASCII.GetString(aBuffer, 0, count);

                            // continue building the string
                            stringBuilder.Append(tempString);
                        }
                    }
                    while (count > 0); // any more data to read?
                }
            }
            catch (Exception ex)
            {
                // Timeout most likely, just return empty string 
                Debug.WriteLine("Exception reading website: " + ex.Message);
            }

            return stringBuilder.ToString();
        }
    }
}
